package com.pig4cloud.pig.homecenter.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.homecenter.entity.HassAreaRegistryEntity;
import com.pig4cloud.pig.homecenter.entity.HassDeviceRegistryEntity;
import com.pig4cloud.pig.homecenter.service.HassAreaRegistryService;
import com.pig4cloud.pig.homecenter.service.HassDeviceRegistryService;
import com.pig4cloud.pig.homecenter.vo.SyncDevicesVO;
import com.pig4cloud.pig.homecenter.vo.SyncEntitiesVO;
import com.pig4cloud.pig.homecenter.vo.SyncEntityVO;
import com.pig4cloud.pig.homecenter.ws.HassWebsocketMessageUtils;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.pig.homecenter.entity.HassEntityRegistryEntity;
import com.pig4cloud.pig.homecenter.service.HassEntityRegistryService;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 实体数据
 *
 * @author pig
 * @date 2025-01-09 13:43:05
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/hassEntityRegistry" )
@Tag(description = "hassEntityRegistry" , name = "实体数据管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class HassEntityRegistryController {

    private final  HassEntityRegistryService hassEntityRegistryService;

	private final HassDeviceRegistryService hassDeviceRegistryService;

	private final HassAreaRegistryService hassAreaRegistryService;

	/**
     * 分页查询
     * @param page 分页对象
     * @param hassEntityRegistry 实体数据
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_view')" )
    public R getHassEntityRegistryPage(@ParameterObject Page page, @ParameterObject HassEntityRegistryEntity hassEntityRegistry) {
        LambdaQueryWrapper<HassEntityRegistryEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.like(StrUtil.isNotBlank(hassEntityRegistry.getCustomeName()),HassEntityRegistryEntity::getCustomeName,hassEntityRegistry.getCustomeName());
		wrapper.eq(StrUtil.isNotBlank(hassEntityRegistry.getAreaId()),HassEntityRegistryEntity::getAreaId,hassEntityRegistry.getAreaId());
		wrapper.eq(StrUtil.isNotBlank(hassEntityRegistry.getShowAs()),HassEntityRegistryEntity::getShowAs,hassEntityRegistry.getShowAs());
		wrapper.eq(hassEntityRegistry.getVisible() != null,HassEntityRegistryEntity::getVisible,hassEntityRegistry.getVisible());
		Page<HassEntityRegistryEntity> res = hassEntityRegistryService.page(page, wrapper);
		res.getRecords().forEach(item->{
			LambdaQueryWrapper<HassDeviceRegistryEntity> deviceWrapper = Wrappers.lambdaQuery();
			deviceWrapper.eq(HassDeviceRegistryEntity::getUserId,item.getUserId());
			deviceWrapper.eq(HassDeviceRegistryEntity::getId,item.getDeviceId());
			HassDeviceRegistryEntity device = hassDeviceRegistryService.getOne(deviceWrapper);
			if(device != null){
				item.setDeviceName(device.getCustomName());
				if(StringUtils.isBlank(item.getAreaId())){
					item.setAreaId(device.getAreaId());
				}
			}
			LambdaQueryWrapper<HassAreaRegistryEntity> areaWrapper = Wrappers.lambdaQuery();
			areaWrapper.eq(HassAreaRegistryEntity::getUserId,item.getUserId());
			areaWrapper.eq(HassAreaRegistryEntity::getAreaId,item.getAreaId());
			HassAreaRegistryEntity area = hassAreaRegistryService.getOne(areaWrapper);
			item.setAreaName(area != null ? area.getName() : null);
		});
        return R.ok(res);
    }

    /**
     * 通过条件查询实体数据
     * @param hassEntityRegistry 查询条件
     * @return R  对象列表
     */
    @Operation(summary = "通过条件查询" , description = "通过条件查询对象" )
    @GetMapping("/details" )
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_view')" )
    public R getDetails(@ParameterObject HassEntityRegistryEntity hassEntityRegistry) {
		List<HassEntityRegistryEntity> res = hassEntityRegistryService.list(Wrappers.query(hassEntityRegistry));
		res.forEach(item->{
			HassWebsocketMessageUtils.configEntityRegistryGet(item.getEntityId());

			LambdaQueryWrapper<HassDeviceRegistryEntity> deviceWrapper = Wrappers.lambdaQuery();
			deviceWrapper.eq(HassDeviceRegistryEntity::getUserId,item.getUserId());
			deviceWrapper.eq(HassDeviceRegistryEntity::getId,item.getDeviceId());
			HassDeviceRegistryEntity device = hassDeviceRegistryService.getOne(deviceWrapper);
			if(device != null){
				item.setDeviceName(device.getCustomName());
				if(StringUtils.isBlank(item.getAreaId())){
					item.setAreaId(device.getAreaId());
				}
			}

			LambdaQueryWrapper<HassAreaRegistryEntity> areaWrapper = Wrappers.lambdaQuery();
			areaWrapper.eq(HassAreaRegistryEntity::getUserId,item.getUserId());
			areaWrapper.eq(HassAreaRegistryEntity::getAreaId,item.getAreaId());
			HassAreaRegistryEntity area = hassAreaRegistryService.getOne(areaWrapper);
			item.setAreaName(area != null ? area.getName() : null);

		});
		return R.ok(res);
    }

    /**
     * 新增实体数据
     * @param hassEntityRegistry 实体数据
     * @return R
     */
    @Operation(summary = "新增实体数据" , description = "新增实体数据" )
    @SysLog("新增实体数据" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_add')" )
    public R save(@RequestBody HassEntityRegistryEntity hassEntityRegistry) {
        return R.ok(hassEntityRegistryService.save(hassEntityRegistry));
    }

    /**
     * 修改实体数据
     * @param hassEntityRegistry 实体数据
     * @return R
     */
    @Operation(summary = "修改实体数据" , description = "修改实体数据" )
    @SysLog("修改实体数据" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_edit')" )
    public R updateById(@RequestBody HassEntityRegistryEntity hassEntityRegistry) {
        return R.ok(hassEntityRegistryService.updateById(hassEntityRegistry));
    }

    /**
     * 通过id删除实体数据
     * @param ids eid列表
     * @return R
     */
    @Operation(summary = "通过id删除实体数据" , description = "通过id删除实体数据" )
    @SysLog("通过id删除实体数据" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(hassEntityRegistryService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param hassEntityRegistry 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_export')" )
    public List<HassEntityRegistryEntity> exportExcel(HassEntityRegistryEntity hassEntityRegistry,Long[] ids) {
        return hassEntityRegistryService.list(Wrappers.lambdaQuery(hassEntityRegistry).in(ArrayUtil.isNotEmpty(ids), HassEntityRegistryEntity::getEid, ids));
    }

    /**
     * 导入excel 表
     * @param hassEntityRegistryList 对象实体列表
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('homecenter_hassEntityRegistry_export')" )
    public R importExcel(@RequestExcel List<HassEntityRegistryEntity> hassEntityRegistryList, BindingResult bindingResult) {
        return R.ok(hassEntityRegistryService.saveBatch(hassEntityRegistryList));
    }


	@Operation(summary = "同步实体信息", description = "接收hass实体信息")
	@PostMapping("/pushEntities")
	public R pushEntities(@RequestBody SyncEntitiesVO vo) {
		if(vo.getSuccess()){
			hassEntityRegistryService.syncHassEntityRegistry(vo.getResult());
		}else{
			log.info(JSON.toJSONString(vo));
		}
		return R.ok();
	}

	@Operation(summary = "获取实体信息详情", description = "获取实体信息详情")
	@PostMapping("/pushEntityDetail")
	public R pushEntityDetail(@RequestBody SyncEntityVO vo) {
		if(!vo.getSuccess()){
			log.info(JSON.toJSONString(vo));
			return R.ok();
		}
		QueryWrapper<HassEntityRegistryEntity> entityQueryWrapper = Wrappers.query();
		entityQueryWrapper.lambda().eq(HassEntityRegistryEntity::getUserId, SecurityUtils.getUser().getId())
				.eq(HassEntityRegistryEntity::getId, vo.getResult().getId());
		HassEntityRegistryEntity curEntity = hassEntityRegistryService.getOne(entityQueryWrapper,false);
		HassEntityRegistryEntity entity = vo.getResult();
		if(curEntity != null){
			curEntity.setName(entity.getName());
			curEntity.setOriginalName(entity.getOriginalName());
			curEntity.setModifiedAt(entity.getModifiedAt());
			curEntity.setConfigEntryId(entity.getConfigEntryId());
			curEntity.setEntityId(entity.getEntityId());
			curEntity.setPlatform(entity.getPlatform());
			curEntity.setUniqueId(entity.getUniqueId());
			curEntity.setDeviceId(entity.getDeviceId());
			if(!StringUtils.isBlank(entity.getAreaId())){
				entity.setAreaId(curEntity.getAreaId());
			}
			curEntity.setAreaId(entity.getAreaId());
			curEntity.setIcon(entity.getIcon());
			curEntity.setDisabledBy(entity.getDisabledBy());
			curEntity.setTranslationKey(entity.getTranslationKey());
			curEntity.setHasEntityName(entity.getHasEntityName());
			curEntity.setHiddenBy(entity.getHiddenBy());
			curEntity.setCapabilities(entity.getCapabilities());
			hassEntityRegistryService.updateById(curEntity);
		}

		return R.ok();
	}


	@Operation(summary = "获取控制面板实体列表", description = "获取控制面板实体列表")
	@PostMapping("/controlPanelList")
	public R controlPanelList() {
		QueryWrapper<HassEntityRegistryEntity> entityQueryWrapper = Wrappers.query();
		entityQueryWrapper.lambda().select(HassEntityRegistryEntity::getDeviceId,HassEntityRegistryEntity::getEntityId,
				HassEntityRegistryEntity::getCustomeName,HassEntityRegistryEntity::getAreaId,HassEntityRegistryEntity::getShowAs,
				HassEntityRegistryEntity::getEntityType,HassEntityRegistryEntity::getCapabilities,HassEntityRegistryEntity::getState,
						HassEntityRegistryEntity::getStateUpdateTime,HassEntityRegistryEntity::getAttributes)

				.eq(HassEntityRegistryEntity::getUserId, SecurityUtils.getUser().getId())
				.eq(HassEntityRegistryEntity::getVisible, true);

		List<HassEntityRegistryEntity> res = hassEntityRegistryService.list(entityQueryWrapper);
		return R.ok(res);
	}

}
